package com.practice.ajCollections010.list.linkedlist;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

/**
 * 遍历
 * @TODO 优雅的移除 LinkedList 中的元素
 */
public class Traversal {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();

        for (int i = 0; i < 10; i++) {
            linkedList.add(Integer.toString(i));
        }

        /**
         * 遍历方式一：fori 形式遍历
         * 优点：可以后去数组下标
         */
        for (int i = 0; i < linkedList.size(); i++) {
            // do something
            System.out.println(linkedList.get(i));
        }

        /**
         * 遍历方式二：foreach 形式遍历
         */
        for (String item :
                linkedList) {
            // do something
            System.out.println(item);
        }

        /**
         * 遍历方式三：
         * while + iterator 或 for + iterator 从头到尾遍历
         * while + LinstIterator 或 for + ListIterator 从头到尾遍历或从尾到头遍历
         */
        Iterator iterator = linkedList.iterator();
        while (iterator.hasNext()) {
            // do something
            System.out.println(iterator.next());
        }
        for (Iterator item = iterator; iterator.hasNext(); ) {
            //do something
            System.out.println(iterator.next());
        }
        ListIterator<String> iterator2 = linkedList.listIterator();
        while (iterator2.hasNext()) {
            // do something
            System.out.println(iterator2.next());
        }
        while (iterator2.hasPrevious()) {
            //do something
            System.out.println(iterator2.next());
        }

        /**
         * 遍历方式四：Java 8 新特性，stream 流的方式遍历
         */
        linkedList.stream().forEach(item -> {
            // to something
            System.out.println(item);
        });
    }
}
